import logging
from wcwidth import wcswidth


class Reporter:
    """生成最终报告。"""

    def __init__(self, mismatched_libs_report, missing_symbols):
        self.mismatched_libs_report = mismatched_libs_report
        self.missing_symbols = missing_symbols

    @staticmethod
    def _cell_width(cell):
        """计算单元格显示宽度"""
        try:
            width = wcswidth(str(cell))
            return width if width is not None else len(str(cell))
        except (TypeError, ValueError):
            return len(str(cell))

    @staticmethod
    def _pad_cell(cell, width):
        """填充单元格到指定宽度"""
        cell_str = str(cell)
        try:
            current_width = wcswidth(cell_str)
            if current_width is None:
                current_width = len(cell_str)
        except (TypeError, ValueError):
            current_width = len(cell_str)
        pad_len = max(0, width - current_width)
        return cell_str + ' ' * pad_len

    def print_table(self, rows):
        """打印格式化的表格"""
        headers = ["问题库", "OC9 状态", "OC9 提供方", "备注"]

        # 计算每一列最大显示宽度
        widths = [self._cell_width(header) for header in headers]
        for row in rows:
            for i, cell in enumerate(row):
                widths[i] = max(widths[i], self._cell_width(cell))

        # 构造表头
        header_line = " | ".join(
            self._pad_cell(header, width)
            for header, width in zip(headers, widths)
        )
        sep_line = "-+-".join('-' * width for width in widths)

        logging.error(header_line)
        logging.error(sep_line)
        for row in rows:
            line = " | ".join(
                self._pad_cell(cell, width)
                for cell, width in zip(row, widths)
            )
            logging.error(line)

    def print_report(self):
        """打印完整的报告"""
        logging.info("\n" + "="*80)
        logging.info("           Go Application Compatibility Report "
                     "(vs. OpenCloudOS 9)")
        logging.info("="*80)

        if not self.mismatched_libs_report and not self.missing_symbols:
            logging.info("\n✅ 结论： 当前应用可以在 OC9 上运行。")
            logging.info("\n所有必需的库文件和函数符号均可以在OC9仓库中找到匹配项。")
        else:
            logging.error("\n❌ 结论：当前应用不可以在 OC9 上运行。")
            logging.error("\n发现以下兼容性问题：")

        if self.mismatched_libs_report:
            logging.error("--- 库依赖差异 ---")
            self.print_table(self.mismatched_libs_report)

        # 只有在没有库不匹配时才显示符号检查结果
        if self.missing_symbols and not self.mismatched_libs_report:
            logging.error("--- 函数符号依赖差异 ---")
            logging.error("  发现 %d 个缺失的符号!", len(self.missing_symbols))
            for symbol in self.missing_symbols[:30]:
                logging.error("    - %s", symbol)
            if len(self.missing_symbols) > 30:
                logging.error("    ... 以及 %d 个更多缺失符号.",
                              len(self.missing_symbols) - 30)
        logging.info("\n" + "="*80)
